import { createStore } from 'vuex'
import axios from 'axios'

export default createStore({
  state: {
    user: {
      username: localStorage.getItem('username') || '',
      token: localStorage.getItem('token') || ''
    },
    theme: 'light'
  },
  mutations: {
    SET_USER(state, user) {
      state.user = user
      localStorage.setItem('username', user.username)
      localStorage.setItem('token', user.token)
    },
    SET_THEME(state, theme) {
      state.theme = theme
    },
    setToken(state, token) {
      state.user.token = token
      localStorage.setItem('token', token)
    },
    setUsername(state, username) {
      state.user.username = username
      localStorage.setItem('username', username)
    }
  },
  getters: {
    currentUser: state => state.user,
    isAuthenticated: state => !!state.user.token
  },
  actions: {
    async login({ commit }, credentials) {
      try {
        const formData = new FormData()
        formData.append('username', credentials.username)
        formData.append('password', credentials.password)

        const response = await axios.post('http://localhost:8000/api/token', formData)
        const token = response.data.access_token
        
        commit('SET_USER', { 
          username: credentials.username, 
          token: token 
        })
        
        return true
      } catch (error) {
        if (error.response) {
          switch (error.response.status) {
            case 401:
              throw new Error('用户名或密码错误')
            case 422:
              throw new Error('请求参数错误')
            default:
              throw new Error('登录失败，请稍后重试')
          }
        } else if (error.request) {
          throw new Error('无法连接到服务器，请检查网络连接')
        } else {
          throw new Error('请求配置错误')
        }
      }
    },
    logout({ commit }) {
      localStorage.removeItem('token')
      localStorage.removeItem('username')
      commit('SET_USER', { username: '', token: '' })
    }
  }
}) 